package com.keyinong.caizhengting.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.LayoutParams;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.keyinong.caizhengting.R;
import com.keyinong.caizhengting.tools.HttpTools;
import com.keyinong.caizhengting.tools.ImageUtils;
import com.keyinong.caizhengting.tools.MyShowDialog;
import com.keyinong.caizhengting.tools.NetWorkUtil;
import com.keyinong.caizhengting.tools.SystemBarTintManager;
import com.keyinong.caizhengting.activity.BookingNoticeActivity;
import com.keyinong.caizhengting.activity.FanqiedingcanActivity;
import com.keyinong.caizhengting.activity.GoodsTwoSortActivity;
import com.keyinong.caizhengting.activity.NewmessageActivity;
import com.keyinong.caizhengting.activity.NewxiaotieshiActivity;
import com.keyinong.caizhengting.activity.QianbaoActivity;
import com.keyinong.caizhengting.activity.XiaotieshiActivity;
import com.keyinong.caizhengting.adapter.AdViewPagerAdapter;
import com.keyinong.caizhengting.adapter.ShangpintuijianAdapter;
import com.keyinong.caizhengting.entity.AppAdsBean;
import com.keyinong.caizhengting.entity.ShangpinEntity;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

/**
 * 首页
 */

public class ShouyeFragment extends Fragment {
    private static final int TYPE_DINNER = 0;
    private static final int TYPE_MARKET = 1;
    ViewGroup group;
    /**
     * 获得首页数据
     */
    ArrayList<ShangpinEntity> infolist;
    HttpTools httptools = null;
    int width;
    int height;
    private ShangpintuijianAdapter shangpintuijianadapter;
    /**
     * 幻灯片
     */
    private ArrayList<View> viewlist;
    private ArrayList<AppAdsBean> adlist;
    private ViewPager vp_ad;
    private ImageView[] indicator_imgs;
    private String id;
    private ScrollView scrollView;
    /**
     * 顶部
     */
    private RelativeLayout rl_tital;
    private TextView mTvLunch;
    private TextView mTvDinner;
    private TextView mTvMarket;
    private TextView mTvWallet;
    private RelativeLayout rl_wancantuijian;
    private GridView grid_hotGoods;
    /**
     * 营养小贴士
     */
    private ImageView iv_pic;
    private TextView tv_name;
    private TextView tv_content;
    private RelativeLayout rl_yingyang;
    private RelativeLayout rl_ying;
    private String xiaotieshiid;
    /**
     * 消息提醒
     */
    private RelativeLayout rl_message;
    private RelativeLayout rl_note;
    private RelativeLayout rl_xx;
    private TextView tv_date;
    private TextView tv_message;
    private TextView tv_note;
    private TextView tv_date2;
    /**
     * 顶部通知按钮
     */
    private ImageButton iv_tongzhi;
    /**
     * 顶部二维码按钮
     */
    private ImageButton iv_erweima;
    private RelativeLayout rl_xiaoxi;
    /**
     * 搜索
     */
    private TextView tv_sousuo;
    private String date;
    private ScrollView sl;
    private MyThread myThread = new MyThread();
    //首页晚餐推荐点击跳转到晚餐界面
    private OnItemClickListener itemclicke = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int position,
                                long id) {
            Intent intent = new Intent();
//			intent.putExtra("productid", infolist.get(position).getId());
            intent.setClass(getActivity(), GoodsTwoSortActivity.class);
            intent.putExtra("type", TYPE_DINNER);
            startActivity(intent);
        }
    };
    private Handler adHandle = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (vp_ad.getCurrentItem() == indicator_imgs.length - 1) {
                        vp_ad.setCurrentItem(0);
                    } else {
                        vp_ad.setCurrentItem(vp_ad.getCurrentItem() + 1);
                    }
                    break;

                default:
                    break;
            }
        }

    };
    private OnPageChangeListener onpage = new OnPageChangeListener() {
        @Override
        public void onPageSelected(int arg0) {
            // setImageBackground(arg0%mImageViews.length);

            // 修改全部的position长度
            int newPosition = arg0 % viewlist.size();
            // 循环设置当前页的标记图
            int length = adlist.size();
            for (int i = 0; i < length; i++) {
                if (i == newPosition) {
                    indicator_imgs[i]
                            .setBackgroundResource(R.drawable.img_rund_focused);
                } else {
                    indicator_imgs[i]
                            .setBackgroundResource(R.drawable.img_rund_unfocused);
                }
            }

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }

        @Override
        public void onPageScrollStateChanged(int arg0) {

        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 透明状态栏
            getActivity().getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // 透明导航栏
//			getActivity().getWindow().addFlags(
//					WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }

        return inflater.inflate(R.layout.fragment_shouye, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        SystemBarTintManager tintManager = new SystemBarTintManager(
                getActivity());
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintColor(getResources().getColor(
                R.color.white_1));
        super.onActivityCreated(savedInstanceState);
        initRes();
        ImageUrl();
        Xiaoxi();

    }

    private void initRes() {
        sl = (ScrollView) getView().findViewById(R.id.sl);
        sl.smoothScrollTo(0, -20);
        rl_xiaoxi = (RelativeLayout) getView().findViewById(R.id.rl_xiaoxi);
        rl_tital = (RelativeLayout) getView().findViewById(R.id.rl_toolbar);
        rl_tital.bringToFront();
        //跳转到二维码界面
        iv_erweima = (ImageButton) getView().findViewById(R.id.iv_erweima);
        iv_erweima.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                ErweimaFragment erweimaFragment = new ErweimaFragment();
                replceFragment(erweimaFragment);
                Meg(3);
            }
        });
        //跳转到通知界面
        iv_tongzhi = (ImageButton) getView().findViewById(R.id.iv_tongzhi);
        iv_tongzhi.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), NewmessageActivity.class);
                startActivity(intent);
            }
        });
        //跳转到晚餐界面
        rl_wancantuijian = (RelativeLayout) getView().findViewById(R.id.rl_wancantuijian);
        rl_wancantuijian.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), GoodsTwoSortActivity.class);
                intent.putExtra("type", TYPE_DINNER);
                startActivity(intent);
            }
        });
        //跳转到小贴士详情界面
        rl_ying = (RelativeLayout) getView().findViewById(R.id.rl_ying);
        rl_ying.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), NewxiaotieshiActivity.class);
                intent.putExtra("id", xiaotieshiid);
                startActivity(intent);
            }
        });
        //跳转到小贴士列表界面
        rl_yingyang = (RelativeLayout) getView().findViewById(R.id.rl_yingyang);
        rl_yingyang.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), XiaotieshiActivity.class);
                startActivity(intent);
            }
        });
        //跳转到午餐界面
        mTvLunch = (TextView) getView().findViewById(R.id.tv_lunch);
        mTvLunch.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), BookingNoticeActivity.class);
                startActivity(intent);
            }
        });
        //跳转到晚餐界面
        mTvDinner = (TextView) getView().findViewById(R.id.tv_dinner);
        mTvDinner.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), GoodsTwoSortActivity.class);
                intent.putExtra("type", TYPE_DINNER);
                startActivity(intent);
            }
        });
        mTvMarket = (TextView) getView().findViewById(R.id.tv_market);
        mTvMarket.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), GoodsTwoSortActivity.class);
                intent.putExtra("type", TYPE_MARKET);
                startActivity(intent);
            }
        });
        mTvWallet = (TextView) getView().findViewById(R.id.tv_wallet);
        mTvWallet.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().startActivity(new Intent(getActivity(), QianbaoActivity.class));
            }
        });

        grid_hotGoods = (GridView) getView().findViewById(R.id.grid_hotGoods);
        grid_hotGoods.setOnItemClickListener(itemclicke);
        scrollView = (ScrollView) getView().findViewById(R.id.sl);
        vp_ad = (ViewPager) getView().findViewById(R.id.vp_ad);
        group = (ViewGroup) getView().findViewById(R.id.viewgroup);
        iv_pic = (ImageView) getView().findViewById(R.id.iv_pic);
        tv_name = (TextView) getView().findViewById(R.id.tv_name);
        tv_content = (TextView) getView().findViewById(R.id.tv_content);
        rl_message = (RelativeLayout) getView().findViewById(R.id.rl_message);
        rl_note = (RelativeLayout) getView().findViewById(R.id.rl_note);
        rl_xx = (RelativeLayout) getView().findViewById(R.id.rl_xx);
        tv_date = (TextView) getView().findViewById(R.id.tv_date);
        tv_message = (TextView) getView().findViewById(R.id.tv_message);
        tv_date2 = (TextView) getView().findViewById(R.id.tv_date2);
        tv_note = (TextView) getView().findViewById(R.id.tv_note);
        //跳转到搜索界面
//		tv_sousuo = (TextView)getView().findViewById(R.id.tv_sousuo);
//		tv_sousuo.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				Intent intent = new Intent(getActivity(),SearchActivity.class);
//				startActivity(intent);
//			}
//		});
        //跳转到消息界面
        rl_message.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), NewmessageActivity.class);
                startActivity(intent);
            }
        });
        //跳转到午餐界面
        rl_note.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), BookingNoticeActivity.class);
                startActivity(intent);
            }
        });
        SharedPreferences spwm = getActivity().getSharedPreferences("spWM",
                Context.MODE_PRIVATE);
        width = spwm.getInt("width", 720);
        height = spwm.getInt("height", 1280);
        //		Tuijianshangpin();
        //		viewpage();
//		ImageUrl();
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        date = sDateFormat.format(new java.util.Date());
//		Xiaoxi();
        myThread.start();
        scrollView.post(new Runnable() {
            @Override
            public void run() {
                scrollView.scrollTo(0, 1000);
            }
        });
    }

    /**
     * 首页消息
     */
    private void Xiaoxi() {
        SharedPreferences sp = getActivity().getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        String token = sp.getString("data", "");
        if (httptools == null) {
            httptools = new HttpTools(getActivity());
        }
        httptools.getHomeMessage(token, new JsonXiaoxi());
    }

    /**
     * 得到幻灯片
     */
    private void ImageUrl() {
        if (NetWorkUtil.isNetwork(getActivity()) == false) {
            Toast.makeText(getActivity(), "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        infolist = new ArrayList<ShangpinEntity>();
        adlist = new ArrayList<AppAdsBean>();
        viewlist = new ArrayList<View>();
        SharedPreferences sp = getActivity().getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        String token = sp.getString("data", "");
        if (httptools == null) {
            httptools = new HttpTools(getActivity());
        }
        httptools.getHomeInfo(token, new JsonGetpictures());
    }

    //幻灯片设置
    private void addViewList() {
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        /**
         * 创建多个item （每一条viewPager都是一个item） 从服务器获取完数据（如文章标题、url地址） 后，再设置适配器
         */
        int adlenth = indicator_imgs.length;
        viewlist.clear();
        for (int i = 0; i < adlenth; i++) {
            View item = inflater.inflate(R.layout.item_viewpager_ad, null);
            viewlist.add(item);
        }
        vp_ad.setAdapter(new AdViewPagerAdapter(getActivity(), viewlist, adlist));
        vp_ad.setOnPageChangeListener(onpage);
        initIndicator();
    }

    private void initIndicator() {
        ImageView roundview;
        int adsize = adlist.size();
        group.removeAllViews();
        for (int i = 0; i < adsize; i++) {
            roundview = new ImageView(getActivity());
            LinearLayout.LayoutParams params_linear = new LinearLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            params_linear.setMargins(7, 10, 7, 10);
            roundview.setLayoutParams(params_linear);
            indicator_imgs[i] = roundview;
            if (i == 0) {
                indicator_imgs[i]
                        .setBackgroundResource(R.drawable.img_rund_focused);
            } else {
                indicator_imgs[i]
                        .setBackgroundResource(R.drawable.img_rund_unfocused);
            }
            ((ViewGroup) group).addView(indicator_imgs[i]);
        }
    }

    @Override
    public void onDestroyView() {
        myThread.setIsStop(true);
        super.onDestroyView();
    }

    public void Meg(int i) {
        Message message = Message.obtain();
        message.what = i;
        FanqiedingcanActivity.mHandler.sendMessage(message);
    }

    private void replceFragment(Fragment fragment) {
        FragmentManager fManager = getFragmentManager();
        FragmentTransaction fTransaction = fManager.beginTransaction();
        fTransaction.replace(R.id.fram_fanqiedingcan, fragment);
        fTransaction.commit();
    }

    public class JsonXiaoxi extends JsonHttpResponseHandler {
        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              JSONObject response) {
            // TODO Auto-generated method stub
            super.onSuccess(statusCode, headers, response);
            try {
                Log.i("info", "晚餐----" + response.toString());

                //晚餐预定消息
                String message1 = response.getString("message");
                if ("".equals(message1)) {
                    rl_message.setVisibility(View.GONE);
                    rl_xx.setVisibility(View.GONE);
                } else {
                    JSONObject message = response.getJSONObject("message");
                    rl_message.setVisibility(View.VISIBLE);
                    rl_xx.setVisibility(View.VISIBLE);
                    String content = message.getString("content");
                    String time = message.getString("time");
                    tv_date.setText(time);
                    tv_message.setText(content);
                }

                //午餐消息
                String note = response.getString("note");
                if (note.equals("") || note.equals("null") || note.equals("暂无取消的订餐")) {
                    rl_note.setVisibility(View.GONE);
                } else {
                    rl_note.setVisibility(View.VISIBLE);
                    //						rl_xiaoxi.setVisibility(View.VISIBLE);
                    rl_xx.setVisibility(View.VISIBLE);
                    tv_date2.setText(date);
                    tv_note.setText(note);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    public class JsonGetpictures extends JsonHttpResponseHandler {
        @Override
        public void onStart() {
            MyShowDialog.showLoadingDialog(ShouyeFragment.this.getActivity(), "请稍后....");
            super.onStart();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            // TODO Auto-generated method stub
            super.onSuccess(statusCode, headers, response);
            MyShowDialog.closeLoadingDialog();
//			initRes();
            try {
                Log.i("info", response.toString());
                //				    JSONObject pictures = response

                //加载幻灯片
                JSONArray pictures = response.getJSONArray("pictures");
                for (int i = 0; i < pictures.length(); i++) {
                    JSONObject object1 = pictures.getJSONObject(i);
                    String pic = object1.getString("pic");
                    adlist.add(new AppAdsBean(pic));
                }
                indicator_imgs = new ImageView[adlist.size()];
                addViewList();
                if (adlist.size() > 1) {
                    myThread.setIsSleep(false);
                }

                //晚餐推荐商品
                JSONArray products = response.getJSONArray("products");
                for (int i = 0; i < products.length(); i++) {
                    JSONObject data = products.getJSONObject(i);
                    id = data.getString("id");
                    String name = data.getString("name");
                    String content = data.getString("content");
                    String price = data.getString("price");
                    String image = data.getString("image");
                    String unit = data.getString("unit");
                    //						arraylength=""+array.length();

                    infolist.add(new ShangpinEntity(id, name, image, content, price, unit));
                }
                shangpintuijianadapter = new ShangpintuijianAdapter(getActivity(), infolist);
                grid_hotGoods.setAdapter(shangpintuijianadapter);
                //				lv.setDivider(null);
//				Utility.setGridViewHeightBasedOnChildren(grid_hotGoods);

                //小贴士
                JSONObject article = response.getJSONObject("article");
                xiaotieshiid = article.getString("id");
                String title = article.getString("title");
                String pic = article.getString("pic");
                String briefv = article.getString("brief");
                //					show_time = article.getString("show_time");
                String content = article.getString("content");
                tv_name.setText(title);
                tv_content.setText(briefv);
                ImageUtils.displayImage(getActivity(), pic + "?imageView2/1/w/360/h/300", iv_pic, R.drawable.wupian1);


            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private class MyThread extends Thread {
        boolean isSleep = true;
        boolean isStop = false;

        @Override
        public void run() {
            //			int i = 0;
            while (!isStop) {
                if (isSleep) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else {
                    try {
                        Thread.sleep(3000);

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    Message msg = new Message();
                    msg.what = 1;
                    adHandle.sendMessage(msg);
                }

            }
        }

        public void setIsSleep(boolean isSleep) {
            this.isSleep = isSleep;
        }

        public void setIsStop(boolean isStop) {
            this.isStop = isStop;
        }
    }
}
